package com.chinasoft.mall.activity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chinasoft.mall.R;
import com.chinasoft.mall.activity.subActivity.HomePageActivity;
import com.chinasoft.mall.activity.subActivity.ProgramListActivity;
import com.chinasoft.mall.activity.subActivity.goods.GoodsActivity;
import com.chinasoft.mall.activity.subActivity.goods.GoodsDetailActivity;
import com.chinasoft.mall.activity.subActivity.more.HomePageMoreActivity;
import com.chinasoft.mall.activity.subActivity.search.SearchActivity;
import com.chinasoft.mall.framework.Config;
import com.chinasoft.mall.framework.ControllerCenter;
import com.chinasoft.mall.framework.LivingGoods;
import com.chinasoft.mall.framework.OrderGoods;
import com.chinasoft.mall.model.ActivityRecorder;
import com.chinasoft.mall.model.response.EpgBean;
import com.chinasoft.mall.model.response.GetGameBean;
import com.chinasoft.mall.service.PushMessageService;
import com.chinasoft.mall.service.ReflushDateService;
import com.chinasoft.mall.util.LocalDataCommend;
import com.chinasoft.mall.util.SystemSetting;
import com.chinasoft.mall.widget.NetImageView;

public class MainActivity extends BaseObserverActivityGroup implements
		OnClickListener {
	protected FrameLayout base_fl_main;
	
	//首页按钮
	private ImageButton homePageButton;
	
	private ImageButton GoodsPageButton;
	
	private ImageButton playingButton;
	
	private ImageButton showListButton;
	
	private ImageButton searchButton;
	
	private Button backButton;
	
	private Button like;
	private Button edit;
	private TextView title;
	private TextView like_btn;
	private NetImageView titleimg;
	private RelativeLayout title_bar_rl;
	private RelativeLayout game;
	private Button close;
	private Button join;
	private TextView ordertitle;
	private ActivityRecorder activityRecorder;
	private Intent intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.basemain);
		initView();
		initData();
		// 默认进入首页
	    this.onClick(homePageButton);
		ControllerCenter.LoadOverDialog();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void showGame(final GetGameBean.Data ggb) {
		// 暂停发送是否需要提示请求
		OrderGoods.goodsids.add(ggb);
//		OrderGoods.isCancle = true;
		ordertitle.setText(ggb.getGoodsName());
		game.setVisibility(View.VISIBLE);
		join.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra(Config.INTENT_OBJ, ggb);
				intent.setClass(MainActivity.this, OrderGoodsActivity.class);
				MainActivity.this.startActivity(intent);
				game.setVisibility(View.GONE);
			}
		});
	}

	private void initData() {
		OrderGoods.init(this);
		LivingGoods.getInstance().invalidate();
		LivingGoods.getInstance().start();
		
		SystemSetting.goodsids = LocalDataCommend.getGoodsSelect(this);
		intent=new Intent();
		intent.setClass(this, ReflushDateService.class);
		startService(intent);
		
		Intent startServiceIntent = new Intent();
		startServiceIntent.setClass(this,
				PushMessageService.class);
		startService(startServiceIntent);
	}

	private void initView() {
		title = (TextView) findViewById(R.id.title);
		like_btn = (TextView) findViewById(R.id.like_btn);
		ordertitle = (TextView) findViewById(R.id.ordertitle);
		game = (RelativeLayout) findViewById(R.id.game);
		title_bar_rl = (RelativeLayout) findViewById(R.id.title_bar_rl);
		titleimg = (NetImageView) findViewById(R.id.titleimg);
		homePageButton = (ImageButton) findViewById(R.id.sy);
		GoodsPageButton = (ImageButton) findViewById(R.id.sp);
		close = (Button) findViewById(R.id.close);
		join = (Button) findViewById(R.id.join);
		playingButton = (ImageButton) findViewById(R.id.playing);
		showListButton = (ImageButton) findViewById(R.id.jmd);
		searchButton = (ImageButton) findViewById(R.id.ss);
		backButton = (Button) findViewById(R.id.index_bt);
		like = (Button) findViewById(R.id.like);
		edit = (Button) findViewById(R.id.edit);
		base_fl_main = (FrameLayout) findViewById(R.id.base_fl_main);
		homePageButton.setOnClickListener(this);
		GoodsPageButton.setOnClickListener(this);
		playingButton.setOnClickListener(this);
		showListButton.setOnClickListener(this);
		searchButton.setOnClickListener(this);
		backButton.setOnClickListener(this);
		like.setOnClickListener(this);
		edit.setOnClickListener(this);
		close.setOnClickListener(this);
		refreshLike();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.close:
//			OrderGoods.isCancle = false;
			game.setVisibility(View.GONE);
			break;
		case R.id.sy:
			if (!(getCurrentActivity() instanceof HomePageActivity)) {
				refreshBaseView();
				setCurrentActivityGroup(HomePageActivity.class, "好享购物",true);
				homePageButton.setImageResource(R.drawable.sy_down);
			} else {
				backCurrentActivity(true);
			}
			break;
		case R.id.sp:
			if (!(getCurrentActivity() instanceof GoodsActivity)) {
				refreshBaseView();
				setCurrentActivityGroup(GoodsActivity.class, "商品",true);
				GoodsPageButton.setImageResource(R.drawable.sp_down);
			} else {
				backCurrentActivity(true);
			}
			break;
		case R.id.playing:
			if (!(getCurrentActivity() instanceof GoodsDetailActivity)) {
				refreshBaseView();
				List<EpgBean> _curebs = LivingGoods.getInstance()
						.getLiving_ebs();
				if (_curebs.size() > 0) {
					EpgBean _cureb = _curebs.get(0);
					setCurrentActivityGroup(GoodsDetailActivity.class,"正在播出", _cureb,true);
				} else {
					Toast.makeText(this, "暂无直播频道", Toast.LENGTH_LONG).show();
				}
				playingButton.setImageResource(R.drawable.playing_down);
			} else {
				backCurrentActivity(true);
			}
			break;
		case R.id.jmd:
			if (!(getCurrentActivity() instanceof ProgramListActivity)) {
				refreshBaseView();
				setCurrentActivityGroup(ProgramListActivity.class, "节目单",true);
				showListButton.setImageResource(R.drawable.jmd_down);
			} else {
				backCurrentActivity(true);
			}
			break;
		case R.id.ss:
			if (!(getCurrentActivity() instanceof SearchActivity)) {
				refreshBaseView();
				setCurrentActivityGroup(SearchActivity.class, "搜索",true);
				searchButton.setImageResource(R.drawable.ss_down);
			} else {
				backCurrentActivity(true);
			}
			break;
		case R.id.index_bt:
			if(getCurrentActivity() instanceof StaffLoginActivity){
				((StaffLoginActivity)getCurrentActivity()).hideSoftInput();
			}
			backCurrentActivity(false);
			break;
		case R.id.like:
			if (!(getCurrentActivity() instanceof HomePageMoreActivity)) {
//				refreshBaseView();
				setCurrentActivity(HomePageMoreActivity.class, "更多",true);
				backButton.setVisibility(View.VISIBLE);
			} else {
				backCurrentActivity(true);
			}
			break;
//			if (LocalDataCommend.getGoodsListBean(this).size() < 1) {
//				new AlertDialog.Builder(this)
//						.setIcon(R.drawable.alert_dialog_icon)
//						.setTitle("暂无收藏")
//						.setPositiveButton("确定",
//								new DialogInterface.OnClickListener() {
//									public void onClick(DialogInterface dialog,
//											int whichButton) {
//
//										/* User clicked OK so do some stuff */
//									}
//								}).create().show();
//			} else {
//				setCurrentActivity(CollectListActivity.class, "收藏");
//			}
//			EpgBean _eb = new EpgBean();
//			_eb.setTHUM("asdsadsadsa");
//			Intent intent = new Intent(
//					myBroadCast.ACTION_INTENT_TEST);
//			intent.putExtra(Config.INTENT_OBJ, _eb);
//			this.sendBroadcast(intent);
		// 编辑
		case R.id.edit:
			if (edit.getText().toString().equals("编辑")) {
				edit.setText("完成");
			} else {
				edit.setText("编辑");
			}
			((CollectListActivity) getCurrentActivity()).stateChangeCollect();
			break;
		default:
			break;
		}
	}

	public void refreshBaseView() {
		homePageButton.setImageResource(R.drawable.sy_up);
		GoodsPageButton.setImageResource(R.drawable.sp_up);
		playingButton.setImageResource(R.drawable.playing_up);
		showListButton.setImageResource(R.drawable.jmd_up);
		searchButton.setImageResource(R.drawable.ss_up);
	}

	/**
	 * 回退Activity
	 */
	public void backCurrentActivity(boolean isLeftToRight) {
		if (activityRecorder.getPreActivity() != null) {
			activityRecorder = activityRecorder.getPreActivity();
			setActivityView(activityRecorder.getCurrentActivityclazz(),false,isLeftToRight);
		}
	}
	
	

	/**
	 * 进入子activity后跳转
	 * 
	 * @param _activityclazz
	 * @throws Exception
	 */
	public void setCurrentActivity(Class<? extends Activity> _activityclazz,
			String activityName, Serializable isz) {
		activityRecorder = new ActivityRecorder(activityName, _activityclazz,
				activityRecorder, isz);
		setActivityView(_activityclazz,false,true);
	}

	public void setCurrentActivity(Class<? extends Activity> _activityclazz,
			Serializable isz) {
		activityRecorder = new ActivityRecorder("", _activityclazz,
				activityRecorder, isz);
		setActivityView(_activityclazz,false,true);
	}

	public void setCurrentActivity(Class<? extends Activity> _activityclazz,
			String activityName, String titleimgurl, Serializable isz) {
		activityRecorder = new ActivityRecorder(activityName, _activityclazz,
				activityRecorder, isz);
		activityRecorder.setImageurl(titleimgurl);
		setActivityView(_activityclazz,false,true);
	}

	public void setCurrentActivity(Class<? extends Activity> _activityclazz,
			String activityName, String titleimgurl) {
		activityRecorder = new ActivityRecorder(activityName, _activityclazz,
				activityRecorder, null);
		activityRecorder.setImageurl(titleimgurl);
		setActivityView(_activityclazz,false,true);
	}

	public void setCurrentActivity(Class<? extends Activity> _activityclazz,
			String activityName,boolean isLeftToRight) {
		activityRecorder = new ActivityRecorder(activityName, _activityclazz,
				activityRecorder, null);
		setActivityView(_activityclazz,false,isLeftToRight);
	}
	
	/**
	 * 
	 * @param clazz
	 * @param sz
	 *            传递数据
	 * @param tracksz
	 *            返回后的回来后的数据
	 */
	public void setResultSz(Serializable tracksz){
		this.activityRecorder.addSz(Config.INTENT_TRACK, tracksz);
	}

	/**
	 * activityGroup之间跳转
	 * 
	 * @param _activityclazz
	 * @throws Exception
	 */
	private void setCurrentActivityGroup(
			Class<? extends Activity> _activityclazz, String activityName,boolean isActivityGroup) {
		activityRecorder = new ActivityRecorder(activityName, _activityclazz,
				null, null);
		setActivityView(_activityclazz,isActivityGroup,true);
	}
	
	private void setCurrentActivityGroup(
			Class<? extends Activity> _activityclazz, String activityName, Serializable isz,boolean isActivityGroup) {
		activityRecorder = new ActivityRecorder(activityName, _activityclazz, null, isz);
		setActivityView(_activityclazz,isActivityGroup,true);
	}

	


	private void setActivityView(Class<? extends Activity> _activityclazz,boolean isActivityGroup,boolean isLeftToRight) {
		initIndex_bt(_activityclazz);
		HashMap<String, Serializable> iszs = activityRecorder.getSzs();
		Intent intent = new Intent(this, _activityclazz);
		intent = intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		Set<String> _ss = iszs.keySet();
		for (String _s : _ss) {
			intent.putExtra(_s, iszs.get(_s));
		}

		View mainView = getLocalActivityManager().startActivity(
				_activityclazz.getSimpleName(), intent).getDecorView();
		mainView.setFocusable(true);
		mainView.setFocusableInTouchMode(true);
		mainView.requestFocus();
		if (!isActivityGroup) {
			if (isLeftToRight) {
				if (base_fl_main.getChildCount() > 0) {

					View view = base_fl_main.getChildAt(0);
					view.startAnimation(AnimationUtils.loadAnimation(this,
							R.anim.out_to_left));

				}
				mainView.startAnimation(AnimationUtils.loadAnimation(this,
						R.anim.in_from_left));

			} else {
				if (base_fl_main.getChildCount() > 0) {

					View view = base_fl_main.getChildAt(0);
					view.startAnimation(AnimationUtils.loadAnimation(this,
							R.anim.out_to_right));

				}
				mainView.startAnimation(AnimationUtils.loadAnimation(this,
						R.anim.in_from_right));
			}
		}
		base_fl_main.removeAllViews();
		base_fl_main.addView(mainView,0);
	}

	public void initIndex_bt(Class<? extends Activity> _activityclazz) {
		if (activityRecorder.getActivityName() != null
				&& activityRecorder.getActivityName().equals("搜索")) {
			title_bar_rl.setVisibility(View.GONE);
		} else {
			title_bar_rl.setVisibility(View.VISIBLE);
		}
		if (activityRecorder.getActivityName() != null
				&& activityRecorder.getActivityName().equals("收藏")) {
			like_btn.setVisibility(View.GONE);
			like.setVisibility(View.GONE);
			edit.setVisibility(View.VISIBLE);
		} else {
			edit.setVisibility(View.GONE);
			like.setVisibility(View.VISIBLE);
			refreshLike();
		}
		
		if (activityRecorder.getActivityName() != null
				&& activityRecorder.getActivityName().equals("更多")) {
			like_btn.setVisibility(View.GONE);
			like.setVisibility(View.GONE);
		}
		
		if (activityRecorder.getActivityName() != null
				&& activityRecorder.getActivityName().equals("推送消息")) {
			like_btn.setVisibility(View.GONE);
			like.setVisibility(View.GONE);
		}
		
		
		if (activityRecorder.getPreActivity() != null) {
			backButton.setVisibility(View.VISIBLE);
			if (activityRecorder.getPreActivity().getActivityName() == null
					|| "".equals(activityRecorder.getPreActivity()
							.getActivityName())) {
//				index_bt.setText(R.string.base_back);
			} else {
//				index_bt.setText(activityRecorder.getPreActivity()
//						.getActivityName());
			}
			if (activityRecorder.getImageurl() != null) {
				titleimg.setVisibility(View.VISIBLE);
				titleimg.setDownloadurl(activityRecorder.getImageurl());
			} else {
				titleimg.setVisibility(View.GONE);
			}
			if (activityRecorder.getActivityName() != null) {
				title.setVisibility(View.VISIBLE);
				title.setText(activityRecorder.getActivityName());
			} else {
				title.setVisibility(View.GONE);
			}
		} else {
			backButton.setVisibility(View.GONE);
			if (activityRecorder.getActivityName() != null){
				title.setVisibility(View.VISIBLE);
				title.setText(activityRecorder.getActivityName());
			}else{
				title.setVisibility(View.GONE);
			}
			titleimg.setVisibility(View.GONE);
		}
		if (activityRecorder.getActivityName() != null
				&& activityRecorder.getActivityName().equals("aboutus")) {
			title.setVisibility(View.GONE);
			like_btn.setVisibility(View.GONE);
			like.setVisibility(View.GONE);
		}
	}

	public void refreshLike() {
		int size = LocalDataCommend.getGoodsListSize(this);
		like_btn.setText(size + "");
		if (size == 0) {
			like_btn.setVisibility(View.GONE);
		} else {
			if (like.isShown()) {
				like_btn.setVisibility(View.VISIBLE);
			}
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (activityRecorder.getPreActivity() != null) {
				backCurrentActivity(false);
			}else{
				Builder dialog = new AlertDialog.Builder(this);
				dialog.setTitle("提示");
				dialog.setMessage("是否退出");
				
				// 创建事件监听器对象
				android.content.DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case DialogInterface.BUTTON1:
							LivingGoods.getInstance().cancle();
//							OrderGoods.setState(true);
							ControllerCenter.getInstance().clear();
							if(intent!=null){
								stopService(intent);
							}
							android.os.Process.killProcess(android.os.Process
									.myPid());
							// 系统退出
							System.exit(0);
							break;
						case DialogInterface.BUTTON2:
							break;
						default:
							break;
						}
					}
				};
				dialog.setPositiveButton(R.string.ensure, onClickListener);
				dialog.setNegativeButton(R.string.cancle, onClickListener);
				dialog.show();
			}
			return true;
		}else{
			return super.onKeyDown(keyCode, event);
		}
	}

//	private ShowPlayingDialog spd;

	@Override
	public void updateActivity(Observable observable, Object data) {
		int refreshtype = (Integer) data;
		if (refreshtype == LivingGoods.Refresh_TS) {/*
			if (spd == null || !spd.isShowing()) {
				spd = new ShowPlayingDialog(this, LivingGoods.getInstance()
						.getEb());
				spd.show();
			}
		*/}
	}
}
